#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    tcpclient=new QTcpSocket(this);
   QString strip=getlocalip();
   ui->comboBox_IP->addItem(strip);//IP地址相同的原因是客户端和服务器在一台电脑

   connect(tcpclient,&QTcpSocket::connected,this,& MainWindow::connectfunc);
   connect(tcpclient,&QTcpSocket::disconnected,this,&MainWindow::disconnectfunc);
    connect(tcpclient,&QTcpSocket::readyRead,this,&MainWindow::socketreaddata);//服务端发数据时触发
}

MainWindow::~MainWindow()
{
    delete ui;
}



QString MainWindow::getlocalip()
{
    QString hostname=QHostInfo::localHostName();
    QHostInfo hostinfo=QHostInfo::fromName(hostname);

    QString localip="";

    QList<QHostAddress> addlist=hostinfo.addresses();
    if(!addlist.isEmpty())
    {
        for (int i=0;i<addlist.count();i++)
        {
            QHostAddress ahost=addlist.at(i);
            if(QAbstractSocket::IPv4Protocol==ahost.protocol())
            {
                localip=ahost.toString();
                break;
            }
        }
    }

    return localip;
}


void MainWindow::on_pushButton_start_clicked()
{
    QString addr=ui->comboBox_IP->currentText();
    quint16 port=ui->spinBox_port->value();
    tcpclient->connectToHost(addr,port);//连接服务器

}

void MainWindow::on_pushButton_stop_clicked()
{
    if(tcpclient->state()==QAbstractSocket::ConnectedState)
    {
        tcpclient->disconnectFromHost();//从服务器断开
    }

}

void MainWindow::on_pushButton_send_clicked()
{
    QString strmsg=ui->lineEdit_message->text();
    ui->plainTextEdit->appendPlainText("[out]:"+strmsg);
    ui->lineEdit_message->clear();//清空输入框

    QByteArray msg=strmsg.toUtf8();//字符串转字节，适配中文
    msg.append("\n");//数据换行
    tcpclient->write(msg);


}

void MainWindow::connectfunc()
{ ui->plainTextEdit->appendPlainText("**********已经连接到服务器端**********");
    ui->plainTextEdit->appendPlainText("**********peer address:"+
                                               tcpclient->peerAddress().toString());
    ui->plainTextEdit->appendPlainText("**********peer port:"+
                                               QString::number(tcpclient->peerPort()));

    ui->pushButton_stop->setEnabled(true);
    ui->pushButton_start->setEnabled(false);

}

void MainWindow::disconnectfunc()
{
    ui->plainTextEdit->appendPlainText("**********已断开与服务器端的连接**********");

    ui->pushButton_start->setEnabled(true);
    ui->pushButton_stop->setEnabled(false);
}

void MainWindow::socketreaddata()
{
//    while(tcpclient->canReadLine())
//    {
//        ui->plainTextEdit->appendPlainText("[in]:"+tcpclient->readLine());
//    }
    ui->plainTextEdit->appendPlainText("[in:]"+tcpclient->readAll());
}
